package com.twu.biblioteca.ui.menus;

import com.twu.biblioteca.app.book.Book;
import com.twu.biblioteca.app.Library;
import com.twu.biblioteca.app.user.User;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

public class BookListMenu extends ItemListMenu{
    private Map<Integer, Book> bookOptions;
    private BufferedReader bufferedReader;

    public BookListMenu(BufferedReader bufferedReader) {
        super(bufferedReader);
        this.bufferedReader = bufferedReader;
        bookOptions = new HashMap<Integer, Book>();

    }

    public String getMenuOptions(Library library) {
        String menuOptions = "";
        menuOptions += "---------------------------------------------\n";
        menuOptions += "AVAILABLE BOOKS\n";
        menuOptions += "---------------------------------------------\n";
        menuOptions += "Please select the book you wish to check out by entering it's option number:\n";
        menuOptions += listAllBooksInLibraryWithOptionNumbers(library);
        return menuOptions;
    }

    protected String listAllBooksInLibraryWithOptionNumbers(Library library) {
        int optionNumber = 1;
        String menuOptions = "";
        for (Book book : library.getAvailableBooks()) {
            menuOptions += optionNumber + ". " + book.getTitle() + " by " + book.getAuthor() + "\n";
            saveBookToOptionNumber(optionNumber, book);
            optionNumber += 1;
        }
        return menuOptions;
    }

    private void saveBookToOptionNumber(int optionNumber, Book book) {
        bookOptions.put(optionNumber, book);
    }

    @Override
    public Library attemptToCheckoutItem(int selection, Library library, User user) {
        return attemptToCheckoutBook(selection, library, user);
    }

    public Library attemptToCheckoutBook(int selection, Library library, User user) {
        Book selectedBook = bookOptions.get(selection);
        if (selectedBook != null && library.checkoutBook(selectedBook, user)) {
            displaySuccessfulCheckoutMessage();
        } else {
            displaySelectionError();
        }
        return library;
    }

    public void displaySelectionError() {
        System.out.print("That book is not available.\n");
    }

    public void displaySuccessfulCheckoutMessage() {
        System.out.print("Thank-you! Enjoy the Book\n");
    }
}
